package org.hzz.pubsub;

import lombok.extern.slf4j.Slf4j;
import org.hzz.redis.JedisSupport;
import redis.clients.jedis.JedisPooled;
import redis.clients.jedis.JedisPubSub;

import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/developeros/videos-online">Code Repository</a>
 * At 2024/9/9
 */
@Slf4j
public class PubSubMain {
    public static JedisPooled jedis = new JedisSupport("localhost",6379).getJedisPool();
    public static Executor executor = Executors.newFixedThreadPool(10);
    public static String channel = UUID.randomUUID().toString();
    public static Semaphore latch = new Semaphore(0);
    public static void main(String[] args) throws InterruptedException {

        executor.execute(PubSubMain::subscribe);
        executor.execute(PubSubMain::publish);

        while(true){
            long start = System.nanoTime();
            latch.tryAcquire(30, TimeUnit.SECONDS);
            long end = System.nanoTime();
            long cost = (end-start)/1000_000_000;
            log.info("cost:{}s",cost);
            if( cost == 30){
                log.info("自动醒来");
            }else{
                log.info("被妈妈叫醒");
            }
        }

    }

    public static void publish(){
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的消息：");
            String msg = scanner.nextLine();
            jedis.publish(channel,msg);
        }
    }

    /**
     * 订阅
     */
    public static void subscribe() {
        JedisPubSub subscriber = new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                log.info("channel:{},message:{}",channel,message);
                latch.release();
            }
        };
        jedis.subscribe(subscriber,channel);
    }
}
